package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.model.agent.CommunityBrokerage;
import com.zbkj.common.model.agent.CommunityStatRecord;
import com.zbkj.common.model.agent.UserCommunity;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.CommunityStat;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.service.dao.CommunityStatDao;
import com.zbkj.service.service.*;

import com.zbkj.common.request.CommunityStatSaveRequest;
import com.zbkj.common.request.CommunityStatSearchRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
* @author Caiyc
* @description CommunityStatServiceImpl 接口实现
* @date 2025-07-21
*/
@Service
public class CommunityStatServiceImpl extends ServiceImpl<CommunityStatDao, CommunityStat> implements CommunityStatService {

    @Resource
    private CommunityStatDao dao;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CommunityStatRecordService communityStatRecordService;
    @Autowired
    private CommunityStatRecordOrderService communityStatRecordOrderService;
    @Autowired
    private CommunityBrokerageService communityBrokerageService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SystemAdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserCommunityService userCommunityService;


    @Override
    public Boolean create(CommunityStatSaveRequest communityStatSaveRequest) {
        CommunityStat communityStat = new CommunityStat();
        BeanUtils.copyProperties(communityStatSaveRequest, communityStat, "id");
        boolean save = save(communityStat);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询小区分红统计表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<CommunityStat>
     * @author Caiyc
     * @since 2025-07-21
     */
    @Override
    public List<CommunityStatPageDataResponse> getList(CommunityStatSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 CommunityStat 类的多条件查询
        LambdaQueryWrapper<CommunityStat> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.orderByDesc(CommunityStat::getCreateTime);
        List<CommunityStat> communityStats = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<CommunityStatPageDataResponse> communityStatResponses = new ArrayList<>();

        communityStats.stream().forEach(x->{
            CommunityStatPageDataResponse communityStatResponse = new CommunityStatPageDataResponse();
            BeanUtils.copyProperties(x, communityStatResponse);
            communityStatResponses.add(communityStatResponse);
        });
        return communityStatResponses;
    }

    /**
    * 修改小区分红统计表
    * @param request
    * @return
    */
    @Override
    public boolean update(CommunityStatSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入小区分红统计表ID");
        }
        getByIdException(request.getId());
        CommunityStat communityStat = new CommunityStat();
        BeanUtils.copyProperties(request, communityStat);
        return updateById(communityStat);
    }

    private CommunityStat getByIdException(Integer id) {
        CommunityStat communityStat = getById(id);
        if (ObjectUtil.isNull(communityStat)) {
            throw new AppException("小区分红统计表不存在");
        }
        if (communityStat.getIsDel()) {
            throw new AppException("小区分红统计表不存在");
        }
        return communityStat;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
    LambdaUpdateWrapper<CommunityStat> luw = Wrappers.lambdaUpdate();
        luw.set(CommunityStat::getIsDel, true);
        luw.in(CommunityStat::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除小区分红统计表失败"));
        }
        return true;
    }

    /**
    * 查询溯源套餐表详情
    * @param id
    * @return
    */
    @Override
    public CommunityStatDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<CommunityStat> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityStat::getIsDel, 0);
        lqw.last("limit 1");
        CommunityStat communityStat = this.getOne(lqw);
        if (ObjectUtil.isNotNull(communityStat)) {
            CommunityStatDetailResponse response = new CommunityStatDetailResponse();
            BeanUtils.copyProperties(communityStat, response);
            return response;
        }
        return null;
    }

    @Override
    public CommunityStatInfoFrontResponse getStatInfo(Integer merId) {
        CommunityStatInfoFrontResponse response = new CommunityStatInfoFrontResponse();
        // 通过商户的小区直接关联查询
        Merchant merchant = merchantService.getCommunityId(merId);
        CommunityStat communityStat = this.getByCommunityId(merchant.getCommunityId());
        if (ObjectUtil.isNull(communityStat)) {
            throw new AppException("商户没有绑定小区");
        }
        BeanUtils.copyProperties(communityStat, response);
        // 排名
        List<CommunityStatRecord> rankingList = communityStatRecordService.getRankingList(communityStat.getId());
        if (CollUtil.isNotEmpty(rankingList)) {
            List<CommunityStatRankingResponse> rankingResponses = new ArrayList<>();
            for (CommunityStatRecord communityStatRecord : rankingList) {
                CommunityStatRankingResponse responseTmp = new CommunityStatRankingResponse();
                BeanUtils.copyProperties(communityStatRecord, responseTmp);
                rankingResponses.add(responseTmp);
            }
            response.setRankingList(rankingResponses);
        }
        return response;
    }

    private CommunityStat getByCommunityId(Integer communityId) {
        LambdaQueryWrapper<CommunityStat> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityStat::getIsDel, false);
        lqw.eq(CommunityStat::getCommunityId, communityId);
        return getOne(lqw);
    }

    @Override
    public MerchantCommunityStatInfoFrontResponse getStatInfoActual(Integer merId) {
        MerchantCommunityStatInfoFrontResponse response = new MerchantCommunityStatInfoFrontResponse();
        Merchant merchant = merchantService.getCommunityId(merId);
        if (merchant == null || merchant.getTypeId() == null) {
            response.setIsShow(false);
            return response;
        }
        // 商户如果是直营的就直接查询小区排行榜数据
        CommunityBrokerage communityBrokerage = null;
        if (merchant.getTypeId().equals(7)) {
            // 加盟店(查询的是店铺自己的设置)
            communityBrokerage = communityBrokerageService.getLatestConfig(merchant.getId(), merchant.getBrandId());
        } else {
            // 直营店
            communityBrokerage = communityBrokerageService.getLatestConfigByCommunity(merchant.getCommunityId());
        }

        if (communityBrokerage == null) {
            // 商户没有启用分红设置
            response.setIsShow(false);
            return response;
        }

        response.setCycle(communityBrokerage.getCycle());
        response.setStartTime(communityBrokerage.getStartTime());
        response.setEndTime(communityBrokerage.getEndTime());
        response.setProfitScale(communityBrokerage.getScale());
        response.setIsSettlement(false);
        response.setPrizeNum(communityBrokerage.getPrizeNum());

        // 小区营业额
        Map<String, Object> map = new HashMap<>();
        map.put("communityId", communityBrokerage.getId());
        map.put("merchantId", merchant.getId());
        map.put("startTime", DateUtil.getSimpleDateFormat(DateUtil.yyyy_MM_dd).format(communityBrokerage.getStartTime()));
        map.put("endTime", DateUtil.getSimpleDateFormat(DateUtil.yyyy_MM_dd).format(communityBrokerage.getEndTime()));

        if(communityBrokerage.getType().equals(1)){
            // 统计总营业额（已扣除品牌商+商户手续费）
            CommunityStatBusinessAmountResponse responseTmp = dao.findBusinessAmountData(map);
            // 统计商户自己的营业额（已扣除商户手续费）
            CommunityStatBusinessAmountResponse responseMerchant = dao.findMerchantBusinessAmountData(map);
            response.setStoreAmount(responseMerchant.getBusinessAmount() != null ? responseMerchant.getBusinessAmount().setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
            response.setBusinessAmount(responseTmp.getBusinessAmount() != null ? responseTmp.getBusinessAmount().setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
            response.setOrderNum(responseTmp.getOrderNum() != null ? responseTmp.getOrderNum() : 0);
            // 未结算金额-总营业额
            CommunityStatBusinessAmountResponse unsettledAmount = dao.findUnsettledBusinessAmountData(map);
            response.setUnsettledAmount(unsettledAmount.getBusinessAmount() != null ? unsettledAmount.getBusinessAmount().setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO);

            // 未结算金额-商户营业额
            CommunityStatBusinessAmountResponse unsettledMerchantAmount = dao.findUnsettledMerchantBusinessAmountData(map);

            // 平台代理给商户设置的分佣比例
//            CommunityBrokerage merchantBrokerageConfig = communityBrokerageService.getMerchantBrokerageRate(merchant.getId());
//            BigDecimal brokerageScale = null;
//            if (merchantBrokerageConfig != null) {
//                if (StrUtil.isNotBlank(merchantBrokerageConfig.getCategoryItems())) {
//                    String[] split = merchantBrokerageConfig.getCategoryItems().split(",");
//                    for (String s : split) {
//                        String[] split1 = s.split("\\:");
//                        Integer id = Integer.parseInt(split1[0]);
//                        if (id.equals(1)) {
//                            // 品牌方默认
//                            brokerageScale = new BigDecimal(split1[1]);
//                        }
//                    }
//                }
//            }
//            if (brokerageScale != null && brokerageScale.doubleValue() > 0) {
//                response.setProfitScale(brokerageScale);
//            }
        }

        // 小区排名
        List<CommunityStatRankingResponse> list = dao.findConsumeRankingList(map);
        // 排名分红
        String[] rankScaleArr = communityBrokerage.getRankingScale().split(",");
        Map<Integer, Double> rankScaleMap = new HashMap();
        for (String rankScaleStr : rankScaleArr) {
            String[] rankScale = rankScaleStr.split("\\:");
            rankScaleMap.put(Integer.parseInt(rankScale[0]), Double.valueOf(rankScale[1]));
        }

        // 当前排名活动可分金额
        BigDecimal currentRankingAmount = response.getBusinessAmount()
                .subtract(response.getUnsettledAmount())
                .multiply(communityBrokerage.getScale())
                .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        response.setProfit(currentRankingAmount);

        if (CollUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                CommunityStatRankingResponse communityStatRankingResponse = list.get(i);
                communityStatRankingResponse.setRankingNum(i + 1);
                communityStatRankingResponse.setGapAmount(BigDecimal.ZERO);
                if (i != 0) {
                    CommunityStatRankingResponse prev = list.get(i - 1);
                    BigDecimal subtract = prev.getTradeAmount().subtract(communityStatRankingResponse.getTradeAmount());
                    communityStatRankingResponse.setGapAmount(subtract);
                }
                // 分红比例
                Double scale = rankScaleMap.get(i + 1);
                if (scale != null && scale > 0) {
                    communityStatRankingResponse.setBrokerageScale(new BigDecimal(scale.toString()));
                    communityStatRankingResponse.setBrokerage(currentRankingAmount
                            .subtract(communityStatRankingResponse.getUnsettledAmount())
                            .multiply(new BigDecimal(scale.toString())).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_DOWN));
                    communityStatRankingResponse.setIsHavePrize(true);
                }
            }
        }
        response.setRankingList(list);
        return response;
    }



    @Override
    public MerchantCommunityStatInfoFrontResponse getMerchantStatInfo(Integer merId) {
        MerchantCommunityStatInfoFrontResponse response = new MerchantCommunityStatInfoFrontResponse();
        // 通过商户的小区直接关联查询
        Merchant merchant = merchantService.getCommunityId(merId);
        // 商户如果是直营的就直接查询小区排行榜数据
        CommunityStat communityStat = null;
        if (BooleanUtil.isTrue(merchant.getIsSelf())) {
            // 加盟店
            communityStat = this.getByMerId(merchant.getId());
        } else {
            // 直营店
            communityStat = this.getByCommunityId(merchant.getCommunityId());
        }

        if (ObjectUtil.isNull(communityStat)) {
            // 查询不到商户分红统计信息
            response.setIsShow(false);
            return response;
        }

        BeanUtils.copyProperties(communityStat, response);
        // 排名
        List<CommunityStatRecord> rankingList = communityStatRecordService.getRankingList(communityStat.getId());
        if (CollUtil.isNotEmpty(rankingList)) {
            List<CommunityStatRankingResponse> rankingResponses = new ArrayList<>();
            for (CommunityStatRecord communityStatRecord : rankingList) {
                CommunityStatRankingResponse responseTmp = new CommunityStatRankingResponse();
                BeanUtils.copyProperties(communityStatRecord, responseTmp);
                rankingResponses.add(responseTmp);
            }
            response.setRankingList(rankingResponses);
        }
        response.setIsShow(true);
        return response;
    }


    private CommunityStat getByMerId(Integer merId) {
        LambdaQueryWrapper<CommunityStat> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityStat::getIsDel, false);
        lqw.eq(CommunityStat::getCommunityId, 0);
        lqw.eq(CommunityStat::getMerId, merId);
        return getOne(lqw);
    }

    @Override
    public void communityBrokerageTask() {
        // 遍历小区列表
        List<CommunityBrokerage> communityList = communityBrokerageService.getCommunityList();
        if (CollUtil.isEmpty(communityList)) {
            return;
        }
        for (CommunityBrokerage communityBrokerage : communityList) {
            // 检查是否有统计数据
            CommunityStat communityStat = this.getByCommunityId(communityBrokerage.getId());
            if (ObjectUtil.isNotNull(communityStat)) {
                continue;
            }
            // 统计该小区下面的排名情况
            CommunityStatInfoFrontResponse communityStatInfoFrontResponse = statRankData(communityBrokerage);
            BeanUtils.copyProperties(communityStatInfoFrontResponse, communityStat);

            communityStat.setCommunity(communityBrokerage.getCommunity());
            communityStat.setCommunityId(communityBrokerage.getId());
            communityStat.setBrandId(communityBrokerage.getBrandId());

            this.save(communityStat);

            List<CommunityStatRecord> recordList = new ArrayList<>();
            for (CommunityStatRankingResponse communityStatRankingResponse : communityStatInfoFrontResponse.getRankingList()) {
                CommunityStatRecord communityStatRecord = new CommunityStatRecord();
                BeanUtils.copyProperties(communityStatRankingResponse, communityStatRecord);
                communityStatRecord.setStatId(communityStat.getId());
                recordList.add(communityStatRecord);
            }
            communityStatRecordService.saveBatch(recordList);
        }
    }


    private CommunityStatInfoFrontResponse statRankData(CommunityBrokerage communityBrokerage) {
        CommunityStatInfoFrontResponse response = new CommunityStatInfoFrontResponse();
        response.setCycle(communityBrokerage.getCycle());
        response.setStartTime(communityBrokerage.getStartTime());
        response.setEndTime(communityBrokerage.getEndTime());
        response.setProfitScale(communityBrokerage.getScale());
        response.setIsSettlement(false);
        response.setPrizeNum(communityBrokerage.getPrizeNum());

        // 小区营业额
        Map<String, Object> map = new HashMap<>();
        map.put("communityId", communityBrokerage.getId());
        map.put("startTime", DateUtil.getSimpleDateFormat(DateUtil.yyyy_MM_dd).format(communityBrokerage.getStartTime()));
        map.put("endTime", DateUtil.getSimpleDateFormat(DateUtil.yyyy_MM_dd).format(communityBrokerage.getEndTime()));
        CommunityStatBusinessAmountResponse responseTmp = dao.findBusinessAmountData(map);
        if (responseTmp != null) {
            response.setBusinessAmount(responseTmp.getBusinessAmount() != null ? responseTmp.getBusinessAmount() : BigDecimal.ZERO);
            response.setOrderNum(responseTmp.getOrderNum() != null ? responseTmp.getOrderNum() : 0);
        }
        if (response.getBusinessAmount().compareTo(BigDecimal.ZERO) == 0) {
            return response;
        }
        // 小区排名
        List<CommunityStatRankingResponse> list = dao.findConsumeRankingList(map);
        // 分红
        String[] rankScaleArr = communityBrokerage.getRankingScale().split(",");
        Map<Integer, Double> rankScaleMap = new HashMap();
        for (String rankScaleStr : rankScaleArr) {
            String[] rankScale = rankScaleStr.split("\\:");
            rankScaleMap.put(Integer.parseInt(rankScale[0]), Double.valueOf(rankScale[1]));
        }

        // 当前排名活动可分金额
        BigDecimal currentRankingAmount = response.getBusinessAmount().multiply(communityBrokerage.getScale()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

        if (CollUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                CommunityStatRankingResponse communityStatRankingResponse = list.get(i);
                communityStatRankingResponse.setRankingNum(i + 1);
                communityStatRankingResponse.setGapAmount(BigDecimal.ZERO);
                if (i != 0) {
                    CommunityStatRankingResponse prev = list.get(i - 1);
                    BigDecimal subtract = prev.getTradeAmount().subtract(communityStatRankingResponse.getTradeAmount());
                    communityStatRankingResponse.setGapAmount(subtract);
                }
                // 分红比例
                Double scale = rankScaleMap.get(i + 1);
                if (scale != null && scale > 0) {
                    communityStatRankingResponse.setBrokerageScale(new BigDecimal(scale.toString()));
                    communityStatRankingResponse.setBrokerage(currentRankingAmount.multiply(new BigDecimal(scale.toString())).setScale(2, BigDecimal.ROUND_DOWN));
                    communityStatRankingResponse.setIsHavePrize(true);
                }
            }
        }
        response.setRankingList(list);
        return response;
    }

    @Override
    public CommunityStatFrontResponse getMyCommunityStat() {
        User user = userService.getInfo();
        UserCommunity userCommunity = userCommunityService.getByUid(user.getId());
        if (ObjectUtil.isNull(userCommunity)) {
            return null;
        }

        CommunityStatFrontResponse response = new CommunityStatFrontResponse();
        // 通过商户的小区直接关联查询
        Merchant merchant = merchantService.getCommunityId(userCommunity.getCommunityId());
        // 商户如果是直营的就直接查询小区排行榜数据
        CommunityStat communityStat = null;
        if (BooleanUtil.isTrue(merchant.getIsSelf())) {
            // 加盟店
            communityStat = this.getByMerId(merchant.getId());
        } else {
            // 直营店
            communityStat = this.getByCommunityId(merchant.getCommunityId());
        }

        if (ObjectUtil.isNull(communityStat)) {
            // 查询不到商户分红统计信息
            response.setIsShow(false);
            return response;
        }

        BeanUtils.copyProperties(communityStat, response);
        // 排名
        List<CommunityStatRecord> rankingList = communityStatRecordService.getRankingList(communityStat.getId());
        if (CollUtil.isNotEmpty(rankingList)) {
            List<CommunityStatRankingResponse> rankingResponses = new ArrayList<>();
            for (CommunityStatRecord communityStatRecord : rankingList) {
                CommunityStatRankingResponse responseTmp = new CommunityStatRankingResponse();
                BeanUtils.copyProperties(communityStatRecord, responseTmp);
                rankingResponses.add(responseTmp);
            }
            response.setRankingList(rankingResponses);
        }
        response.setIsShow(true);
        return response;
    }

    @Override
    public MerchantCommunityStatInfoFrontResponse getCommunityStat(Integer comId) {
        MerchantCommunityStatInfoFrontResponse response = new MerchantCommunityStatInfoFrontResponse();
        // 查询小区排行榜数据
        CommunityStat communityStat = this.getByCommunityId(comId);
        if (ObjectUtil.isNull(communityStat)) {
            // 查询不到商户分红统计信息
            response.setIsShow(false);
            return response;
        }

        BeanUtils.copyProperties(communityStat, response);
        // 排名
        List<CommunityStatRecord> rankingList = communityStatRecordService.getRankingList(communityStat.getId());
        if (CollUtil.isNotEmpty(rankingList)) {
            List<CommunityStatRankingResponse> rankingResponses = new ArrayList<>();
            for (CommunityStatRecord communityStatRecord : rankingList) {
                CommunityStatRankingResponse responseTmp = new CommunityStatRankingResponse();
                BeanUtils.copyProperties(communityStatRecord, responseTmp);
                rankingResponses.add(responseTmp);
            }
            response.setRankingList(rankingResponses);
        }
        response.setIsShow(true);
        return response;
    }


}

